<template>
  <div class="rule-management-container">
    <div class="page-header">
      <h2 class="page-title">规则管理</h2>
      <div class="upload-container">
        <input 
          type="file" 
          id="ruleUpload" 
          ref="fileInput" 
          accept=".xlsx,.xls"
          style="display: none"
          @change="handleFileChange"
        >
        <button class="btn-primary" @click="triggerFileInput">
          <i class="fas fa-upload"></i> 上传规则
        </button>
        <span v-if="uploadStatus" class="upload-status">
          {{ uploadStatus }}
        </span>
      </div>
    </div>
    
    <div class="table-container">
      <div v-if="loading" class="loading-indicator">
        <i class="fas fa-spinner fa-spin"></i> 加载中...
      </div>
      
      <div v-else-if="error" class="error-message">
        <i class="fas fa-exclamation-circle"></i> {{ error }}
        <button class="btn-primary retry-btn" @click="fetchRuleList">重试</button>
      </div>
      
      <table v-else class="rule-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>规则文件名</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="rule in ruleList" :key="rule.id">
            <td>{{ rule.id }}</td>
            <td>{{ rule.ruleFileName }}</td>
            <td>{{ formatDate(rule.createTime) }}</td>
            <td>
              <!-- <button class="btn-action">
                <i class="fas fa-download"></i> 下载
              </button>-->
              <button class="btn-action btn-danger" @click="confirmDelete(rule.id)">
                <i class="fas fa-trash"></i> 删除
              </button> 
            </td>
          </tr>
          <tr v-if="ruleList.length === 0">
            <td colspan="4" class="no-data">暂无规则数据</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRuleManagement } from '../scripts/ruleManagement'
import { API_URL } from '../config/apiConfig'
import { addAuthHeader } from '../scripts/api/apiUtils'

const fileInput = ref<HTMLInputElement | null>(null)
const uploadStatus = ref('')

const {
  ruleList,
  loading,
  error,
  fetchRuleList,
  formatDate,
  deleteRule
} = useRuleManagement()

onMounted(() => {
  fetchRuleList()
})

const confirmDelete = async (ruleId: string) => {
  if (!confirm('确定要删除这条规则吗？此操作不可恢复。')) {
    return
  }
  
  const success = await deleteRule(ruleId)
  if (success) {
    alert('规则删除成功')
  } else {
    alert('规则删除失败，请重试')
  }
}

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return

  try {
    uploadStatus.value = '上传中...'
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch(`${API_URL}/demo/rule/upload`, addAuthHeader({
      method: 'POST',
      credentials: 'include',
      body: formData
    }))

    if (!response.ok) {
      throw new Error(`上传失败: ${response.status}`)
    }

    uploadStatus.value = '上传成功'
    await fetchRuleList()
  } catch (err) {
    console.error('上传规则文件失败:', err)
    uploadStatus.value = '上传失败'
  } finally {
    // 重置文件输入
    if (target) target.value = ''
    // 3秒后清除状态
    setTimeout(() => {
      uploadStatus.value = ''
    }, 3000)
  }
}
</script>

<style scoped>
.rule-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.upload-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-status {
  font-size: 14px;
  color: #666;
}

.upload-status::before {
  content: "•";
  margin-right: 5px;
  color: var(--success-color, #28a745);
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.rule-table {
  width: 100%;
  border-collapse: collapse;
}

.rule-table th,
.rule-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.rule-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.rule-table tr:hover {
  background-color: #f8f9fa;
}

.btn-action {
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  padding: 6px 10px;
  margin-right: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-action:hover {
  background-color: #e0e0e0;
}

.btn-danger {
  color: #dc3545;
}

.btn-danger:hover {
  background-color: #ffebee;
}

.loading-indicator {
  padding: 30px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.error-message {
  padding: 30px;
  text-align: center;
  color: #dc3545;
  font-size: 16px;
}

.retry-btn {
  margin-left: 10px;
  padding: 6px 12px;
}

.no-data {
  text-align: center;
  color: #666;
  padding: 30px;
}
</style>